package net.zjitc.jdbc;

import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @Author admin
 * @Date 2019/4/24 10:30
 * 用预编译方式操作SQL
 */
public class PreparedStatementTest {
    public static void main(String[] args) {
        /*1、加载驱动
        * 2、获得数据库连接
        * 3、获得操作SQL语句的对象：PreparedStatement
        * 4、执行SQL语句(增删改)
        * 5、关闭*/
        Scanner scannerInt=new Scanner(System.in);
        Scanner scannerString=new Scanner(System.in);
        Connection conn=null;
        PreparedStatement pstmt=null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/lgy";
            String user="root";
            String password="123456";
            conn= DriverManager.getConnection(url,user,password);
            String sql="insert into user(name,age) values(?,?)";
            pstmt=conn.prepareStatement(sql);
            System.out.println("请输入用户名：");
            String name=scannerString.nextLine();
            System.out.println("请输入年龄：");
            int age=scannerInt.nextInt();
           pstmt.setString(1,name);
           pstmt.setInt(2,age);
            int s=pstmt.executeUpdate();
            System.out.println("影响了"+s+"行");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (pstmt!=null){
                    pstmt.close();
                }
                if (conn!=null){
                    conn.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
